package com.zsrt.devbase.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.junit.Test;

import com.alibaba.fastjson.JSON;

/**
 * 1000：当前用户已经登录（同一帐号不能同时在两处登录） 
 * 1002：登录被拒绝（一般是账号或者密码错误了） 1004: 登录IP错误
 * 2001：短信发送失败 
 * 2002：短信库存不足 
 * 2003：存在无效的手机号码 
 * 2008：短信签名不正确或者没有签名（签名格式为【XXXX】）
 * 2009:短信模版错误或者编码错误 
 * 3001：没有要接收的短信 
 * 3002：没有要接收的回复状态
 * 9002：SendDate或SendTime参数不是有效日期
 * 9003：短信内容长度超过
 * 300(短信内容为空也会报这个错误或者参数名称错误)
 * 9004：参数不符合要求（输出提交参数 对照举例 看看是否参数填写错误） 
 * 9099：其它系统错误；
 * @author leixin
 * @Date 2017年4月13日
 * @version 1.0
 */
public class SendPhoneCodeUtil {

	private static Logger logger = Logger.getLogger(SendPhoneCodeUtil.class);
	private static String UESRID = "702333";
	private static String ACCOUNT = "17603021475";
	private static String SIGN = "【浪驰软件】";
	private static String PASSWORD = "40257A705A6B0B61FD7384BE6D03692B813EC702";
	
	
	/**
	 * 
	 * @author leixin
	 * @createTime 上午11:51:30
	 * @param phoneNums
	 * @param content
	 * @throws IOException
	 */
	public static Map<String, String> sendCode(String phoneNums , String content) throws IOException {
		URL url = new URL("http://www.lanz.net.cn/LANZGateway/DirectSendSMSs.asp");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "GB2312");
		//拼接字符串
		StringBuilder urlBuilder = new StringBuilder();
		urlBuilder.append("UserID=").append(UESRID);
		urlBuilder.append("&Account=").append(ACCOUNT);
		urlBuilder.append("&Password=").append(PASSWORD);
		urlBuilder.append("&Content=").append(content);
		urlBuilder.append(SIGN);
		urlBuilder.append("&Phones=").append(phoneNums);
		urlBuilder.append("&ReturnXJ=1");
		String urlString = urlBuilder.toString();

		urlString = urlString.replace("%", "％");
		urlString = urlString.replace("+", "＋");
		urlString = urlString.replace(" ", "+");

		out.write(urlString);
		out.flush();
		out.close();

		String sCurrentLine;
		String sTotalString;
		sCurrentLine = "";
		sTotalString = "";
		InputStream l_urlStream;
		l_urlStream = connection.getInputStream();

		BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream));
		while ((sCurrentLine = l_reader.readLine()) != null) {
			sTotalString += sCurrentLine + "\r\n";
		}
		logger.info(sTotalString);
		Map<String, String> result= null;
		try {
			result = paserStr(sTotalString);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("短信验证码发送异常");
			e.printStackTrace();
		}
		return result;
	}
	
	
	@SuppressWarnings("rawtypes")
	public static Map<String, String> paserStr(String str){
//		String str = "{\"LANZ_ROOT\":{\"ErrorNum\":\"0\",\"JobID\":\"49282627\",\"PhonesSend\":\"1\",\"ErrPhones\":\"\",\"DeductionSMSs\":\"1\"}}";
	
		//打印输出发送结果
		logger.info(str);
		//将打印结果转换为map
		Map<?, ?> maps = (Map<?, ?>)JSON.parse(str); 
		String string = maps.get("LANZ_ROOT").toString();
		Map<?, ?> temp = (Map<?, ?>)JSON.parse(string);
		Map<String, String> result = new HashMap<>();
		//将打印结果再次转换为map（真正需要的结果）
		for (Object map : temp.entrySet()) {
			result.put(((Map.Entry)map).getKey().toString(), ((Map.Entry)map).getValue().toString());
		}
		/**
		 * 返回的map中如果ErrorNum = 0，则表示发送成功
		 */
		return result;
	}
	
	@Test
	public void testName() throws Exception {
		String content = "您的注册验证码为8268，该验证码10分钟内有效。如非本人操作请忽略此短信！";
		String phoneNums = "13027517559";
		Map<String, String> sendCode = sendCode(phoneNums, content);
		System.err.println(sendCode.toString());
	}
	
	
}